/**
 * 项目名称: Topic_652.cpp
 * 项目路径: study/DataStructure/LeetCode/树/中等
 * 编辑时间: 2024年09月01日15时54分04秒
 * 用   户: 轻尘
 */

#include <bits/stdc++.h>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

/**
 * 本题采用三元组的方法,通过不断递归,判断子树中是否出现重复
 */
class Solution {
public:
    unordered_map<string, int> ids;
    int cnt = 0;
    unordered_map<int, int> hash;
    vector<TreeNode *> ans;

    int pre(TreeNode *root) {
        if (!root)return 0;
        int left = pre(root->left);
        int right = pre(root->right);
        string key = to_string(root->val) + ' ' + to_string(left) + ' ' + to_string(right);
        if (ids.count(key) == 0)ids[key] = ++cnt;
        int id = ids[key];
        if (++hash[id] == 2)ans.push_back(root);
        return id;
    }

    vector<TreeNode *> findDuplicateSubtrees(TreeNode *root) {
        pre(root);
        return ans;
    }
};
